package froxy.client;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SwingUI extends JFrame implements GUIActoin {
    /** 
     *  
     */
    private static final long serialVersionUID = 1L;
    private static Log        logger           = LogFactory.getLog(SwingUI.class);
    private TrayIcon          ti;
    private static SwingUI    instance;
    private JLabel            jCount;
    private JComboBox         remote;

    public static SwingUI getApplicatoin() {
        return instance;
    }

    public static void main(String[] args) throws Exception {
        SwingUI frame = new SwingUI();
        instance = frame;
        frame.setTitle("Froxy Http");
        frame.setVisible(true);
        frame.setSize(580, 90);
        frame.setLocation(300, 200);
        new Thread(new HttpProxyServer(), "HttpServer").start();
    }

    public SwingUI() {
        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (SystemTray.isSupported()) {
                    setVisible(false);
                    minimizeToTray();
                } else {
                    System.exit(0);
                }
            }
        });
        JPanel root = new JPanel();

        remote = new JComboBox();
        for (int i = 0; i < Helper.REMOTE_SERVERS.length; i++) {
            remote.addItem(Helper.REMOTE_SERVERS[i]);
        }
        remote.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                logger.info("User selects proxy " + ((JComboBox) e.getSource()).getSelectedItem());
                Helper.REMOTE_SERVER = ((JComboBox) e.getSource()).getSelectedIndex();
            }
        });

        JLabel info = new JLabel();
        info.setText("Froxy started at port " + Helper.getFroxyPort());
        JButton config = new JButton("ReConfig");
        config.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                Helper.loadProperties();
            }
        });      
        jCount = new JLabel();
        jCount.setText("and fetched " + Helper.count);
        root.add(remote);
        root.add(config);
        root.add(info);
        root.add(jCount);
        if (Helper.getDecryptClass() != null) {
            addEncryption(root);
        } else {
            Helper.ENCRIPT_ENABLEED = false;
        }
        getContentPane().add(root);
        pack();
        initTi();
    }

    private void addEncryption(JPanel root) {
        JCheckBox encrypt = new JCheckBox("Encrypt");
        encrypt.setSelected(Helper.ENCRIPT_ENABLEED);
        encrypt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (((JCheckBox) e.getSource()).isSelected()) {
                    Helper.ENCRIPT_ENABLEED = true;
                    logger.info("Encrypt the body of message");
                } else {
                    Helper.ENCRIPT_ENABLEED = false;
                    logger.info("Not encrypt the body of message");
                }
            }
        });
        root.add(encrypt);
    }

    private void initTi() {
        Image image = Toolkit.getDefaultToolkit().getImage("logo.png");
        PopupMenu popupTi = new PopupMenu();
        MenuItem showItem = new MenuItem("Show");
        ActionListener showListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(true);
                SystemTray.getSystemTray().remove(ti);
            }
        };
        showItem.addActionListener(showListener);
        popupTi.add(showItem);
        MenuItem exitItem = new MenuItem("Exit");
        ActionListener exitListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        };
        exitItem.addActionListener(exitListener);
        popupTi.add(exitItem);

        ti = new TrayIcon(image, "Froxy", popupTi);
        ti.addActionListener(showListener);
    }

    public void minimizeToTray() {
        SystemTray tray = SystemTray.getSystemTray();
        try {
            tray.add(ti);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    public void updateFetchCount() {
        jCount.setText("and fetched " + Helper.count);
    }

    public void updateRemoteServer() {
        remote.setSelectedIndex(Helper.REMOTE_SERVER);
    }
}
